package lesson11;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class MyReentrantLock {



    private int count = 0;

    private AtomicReference<Thread> owner = new AtomicReference<>();

    public void lock(){
        Thread current = Thread.currentThread();
        if(current == owner.get()){
            count++;
            System.out.println(Thread.currentThread().getName() + " 锁重入。。");
            return;
        }

        while (!owner.compareAndSet(null, current)){
            System.out.println(Thread.currentThread().getName() + " 自旋。。");
        }
    }

    public void unlock(){
        Thread current = Thread.currentThread();
        if(current == owner.get()){
            if(count > 0){
                count --;
            }else{
                owner.set(null);
            }
        }
    }

    public static void main(String[] args) {

        MyReentrantLock myReentrantLock = new MyReentrantLock();

        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName() + "开始尝试获取自旋锁");
            myReentrantLock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获取到了自旋锁");
                Thread.sleep(400);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                System.out.println(Thread.currentThread().getName() + "释放了自旋锁");
                myReentrantLock.unlock();
            }
        };


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(10));

        for(int i = 0; i < 10; i++){

            threadPoolExecutor.execute(runnable);

        }

    }
}
